package com.data.modules.oss.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.data.common.exception.BootException;
import com.data.common.util.CommonUtils;
import com.data.common.constant.enums.ContractEnum;
import com.data.common.util.DateUtils;
import com.data.common.util.oss.OssBootUtil;
import com.data.modules.oss.entity.OSSFile;
import com.data.modules.oss.mapper.OSSFileMapper;
import com.data.modules.oss.service.IOSSFileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service("ossFileService")
public class OSSFileServiceImpl extends ServiceImpl<OSSFileMapper, OSSFile> implements IOSSFileService {

	@Override
	public String upload(MultipartFile multipartFile) throws IOException {
		String fileName = multipartFile.getOriginalFilename();
		fileName = CommonUtils.getFileName(fileName);
		OSSFile ossFile = new OSSFile();
		ossFile.setFileName(fileName);
		String monthStr = DateUtils.formatDate();//String.valueOf(DateUtils.getCurrentTimestamp());
		String url = OssBootUtil.upload(multipartFile,monthStr);
		//update-begin--Author:data-boot  Date:20201227 for：JT-361【文件预览】阿里云原生域名可以文件预览，自己映射域名kkfileview提示文件下载失败-------------------
		// 返回阿里云原生域名前缀URL
		ossFile.setUrl(OssBootUtil.getOriginalUrl(url));
		//update-end--Author:data-boot  Date:20201227 for：JT-361【文件预览】阿里云原生域名可以文件预览，自己映射域名kkfileview提示文件下载失败-------------------
		this.save(ossFile);
		if(ObjectUtil.isEmpty(url)){
			throw new BootException(ContractEnum.PROMPT_INFORMATION_ERROR_3.getMsg());
		}
		return url;
	}

	@Override
	public boolean delete(OSSFile ossFile) {
		try {
			this.removeById(ossFile.getId());
			OssBootUtil.deleteUrl(ossFile.getUrl());
		}
		catch (Exception ex) {
			return false;
		}
		return true;
	}

}
